package stringbuilder;
/*
*
*利用StringBuilder()拼接
* */
public class StringBuilderDemo09 {
    public static void main(String[] args) {
        //method01();
        method02();

    }

    private static void method02() {
        //1.定义一个整数数组
        int[] arr = {15,17,21,32};
        //2.创建一个容器，初始值为"["
        StringBuilder sb = new StringBuilder("[");
        //3.通过遍历拼接
        for (int i = 0; i < arr.length; i++) {
            sb.append(arr[i]);
            if(i!=arr.length-1){
                sb.append(",");
            }
        }
        sb.append("]");
        System.out.println(sb);  // [15,17,21,32]
    }

    private static void method01() {
        //1.定义一个整数数组
        int[] arr = {15,17,21,32};
        //2.首先我们定义一个字符串变量初始值 "[ ",利用Str来反复拼接
        String str = "[";
        //3.拼接数组中的元素包括","
        for (int i = 0; i < arr.length; i++) {
            //str=str+arr[i]+",";       // str = "[" + 15 +"," = “[ 15,”
                                     // str = "[" + 15 +","+17+"," = “[ 15,17,”
            str +=arr[i]; // 所有元素都会拼接  [15172132
            if(i!=arr.length-1){  // 如果不是最后一个元素拼接 “,”
                str+=",";       // [15,17,21,32
            }

        }
        //4.拼接右中括号 “]”
        str+="]";
        System.out.println(str);  // [15,17,21,32,]
    }
}
